package titt.server.func;

import titt.head.HeadFactory;
import titt.head.Header;
import titt.head.Content;
import titt.head.ContentHead;
import titt.head.request.MethodHead;
import titt.head.response.ResponseHead;
import titt.io.socket.TITTSocket;
import titt.key.TITTKey;
import titt.server.os.ObjectServer;
import titt.server.service.Service;
import titt.service.ServicePackage;

public class ServiceWithdraw implements TITTFunction {

	public String getMethodName() {
		return "withdraw";
	}

	
	public void handle(TITTKey key, MethodHead head, TITTSocket ts, ObjectServer os) throws Exception {
		try {
							
			String serviceID = head.getParams()[0].getObject();

			Service s = os.getServerDatabase().get(serviceID);
			
			ServicePackage pack = s == null? null : s.withdraw();		
			
			if(pack == null) {
				ts.getHeadWriter().writeHead(new ResponseHead(404, HeadFactory.EMPTY));
				ts.close();
				return;
			}

			ContentHead c = new Content(pack.getHead());

			ts.getHeadWriter().writeHead(new ResponseHead(200, HeadFactory.createHead(new Header("E-Tag", pack.getPackageID()))));
			ts.getHeadWriter().writeHead(pack.getHead());
			
			try {
				if(c.containsContentLength())
					os.getStreamPiper().pipe(pack.getTITTSocket().getInputStream(), ts.getOutputStream(), c.getContentLength(), pack.getAssociatedListener());
			}
			catch(Exception e) {
				//TODO: check if this is enough error handling
				pack.getTITTSocket().close();
			}
			
		//	pack.getTITTSocket().close();
			ts.close();
		}
		catch(Exception e) {
			//e.printStackTrace();
			//TODO: check if this is enough error handling
			if(!ts.isClosed())
				ts.close();
		}
	}

}
